package de.koller.aframe.util.web.basicHTML;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

abstract public class HTMLPage implements IPage {
	
	protected boolean printHTTP = true;
	protected final BasicWebServer webroot;
	private String request;

	public HTMLPage( BasicWebServer webroot ) {
		this.webroot = webroot;
	}
		
	@Override
	public final void print( OutputStream out, String request ) throws IOException {
		BufferedWriter o = new BufferedWriter( new OutputStreamWriter( out ) );
		if( printHTTP ) {
			o.write( "HTTP/1.0 200 OK\n" );
			o.write( "Content-Type: text/html; charset=UTF-8\n\n" );
		}
		
		this.request = request;
		o.write( getDocType() );
		
		o.write( "<html>" );
			o.write( "<head>" );
				o.write( "<title>" + getPageTitle() + "</title>" );
				o.write( "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" );
				o.write( getHeader() );
			o.write( "</head>" );
			o.write( "<body>" );
				o.write( getBody() );
			o.write( "</body>" );
		o.write( "</html>\n" );
		
		o.flush();
	}
	
	abstract protected String getPageTitle();
	
	@Override
	public boolean isRequestValid( String request ) {
		return true;
	}
	
	protected String getBody() {
		return "";
	}
	
	protected String getHeader() {
		return "";
	}
	
	public final String getRequest() {
		return request;
	}
	
	public String getDocType() {
		return "<!DOCTYPE html>";
	}
	
	public String paragraph( String content ) {
		return "<p>" + content + "</p>";
	}
	
	public String link( String location, String text ) {
		return "<a href=\"" + location + "\" >" + text + "</a>";
	}

	public String image( String location, int w, int h ) {
		return "<img src=\"" + location + "\" alt=\"Bild\" height=\"" + h + "\" width=\"" + w + "\" />";
	}
	
	public String table( String[][] content, int border ) {
		String t = "<table border=\"" + border + "\">";
		
		for( int y = 0; y < content[0].length; y++ ) {
			t += "<tr>";
			for( int x = 0; x < content.length; x++ )
				t += "<td>" + content[x][y] + "</td>";
			t += "</tr>";
		}
		
		t += "</table>";
		
		return t;
	}
	
	public String text( String text, int color, int size ) {
		String t = "<font ";
		t += "color=\"" + Integer.toHexString( color ) + "\" ";
		t += "size=\"" + size + "\" >";
		t += text;
		t += "</font>";
		return t;
	}
	
}
